<?php
/**
 * Created by PhpStorm.
 * User: LG
 * Date: 2017/10/9
 * Time: 17:36
 */

/*
 * 计划任务
 * 李港
 */
namespace app\Cron\controller;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\common\model\Contract;
use app\common\model\ContractEquipment;
use app\common\model\WorkOrder;
use think\Db;

class Cron extends Command
{
    protected function configure()
    {
        $this->setName('Expire')->setDescription('Expire Start');
    }

    protected function execute(Input $input, Output $output)
    {
        $result = $this->Expire();
        $output->writeln("ExpireEnd:".$result);
    }

    /*
     *  合同到期时间/换芯时间并生成相应的工单（和设备相关联）
     *  @author 李港
     */
    public function Expire()
    {
        //判断执行时间
//        if (date('H') != '02'){
//            return date('Y-m-d H:i:s')." Error: It's not the execution time yet";
//        }
        ini_set("max_execution_time", "0");//设置请求时长

        $Contract =  new Contract();
        $ContractEquipment =  new ContractEquipment();
        $WorkOrder =  new WorkOrder();
        $field = '
            contract_id,
            user_id,
            administrative_id,
            operation_id,
            contract_money,
            province,
            city,
            area,
            contact_person,
            phone,
            contract_no,
            for_core_time,
            is_Expire,
            is_Core,
            exire_date
            ';
        $where['contract_no']=['neq','0'];
        $where['contract_status']=1;
        //获取数据
        $data = $Contract->selectData($where,$field);
        if (empty($data)){
           return date('Y-m-d H:i:s')." Error:no data";
        }
        //一个月的秒数
        $one_month_time = 30*24*60*60;
        $time = time();

        //获取设备条件
        $EquipmentJoin = [
            ['rq_equipments','rq_contract_equipment.equipments_id = rq_equipments.equipments_id']
        ];
        $EquipmentField = '
                    rq_contract_equipment.id,
                    rq_contract_equipment.equipments_number,
                    rq_contract_equipment.equipments_address,
                    rq_contract_equipment.contract_id,
                    rq_contract_equipment.equipments_id,
                    rq_equipments.equipments_name
             ';

        //更新时间
        $updateData['update_time'] = $time;

        //操作记录
        $Log = [
            'do_id'=>0,
            'do_type'=>3,
            'terminal_type'=>0,
            'do_time'=>$time,
            'old_value'=>'',
        ];

        //工单数据
        $workOrderData = [
            'repair_id'=>0,
            'business_id'=>1,
            'combo_type'=>'无',
            'reception_user'=>2,
            'work_order_status'=>2,
            'order_time'=>$time,
            'update_time'=>$time,
        ];

        //执行数据库操作
        Db::startTrans();
        try{
            foreach ($data as $key => $value){
            //获取合同设备
            $EquipmentWhere = [
                'contract_id'=>$value['contract_id']
            ];
            //获取设备信息
            $Equipment = $ContractEquipment->getEquipmentsData($EquipmentWhere,$EquipmentJoin,$EquipmentField);
            //更新条件和数据
            $where['contract_id'] = $value['contract_id'];

            //工单数据
            $workOrderData['user_id'] = $value['user_id'];
            $workOrderData['contract_id'] = $value['contract_id'];
            $workOrderData['administrative_id'] = $value['administrative_id'];
            $workOrderData['operation_id'] = $value['operation_id'];
            $workOrderData['combo_money'] = $value['contract_money'];
            $workOrderData['contacts'] = $value['contact_person'];
            $workOrderData['contact_number'] = $value['phone'];

            //判断合同到期时间是否符合
            if ($value['exire_date'] + $one_month_time <= $time && $value['is_Expire'] != 1){
                $updateData['is_Expire'] = 1;
                //更新状态
                $result = $Contract->updateContractExpire($where,$updateData);
                if ($result != 0){
                    $Log['contract_id'] = $value['contract_id'];
                    $Log['new_value'] = '合同和换芯即将到期';
                    //添加日志
                    $Contract->addContractLogExpire($Log);
                }
                //派发合同到期工单
                foreach ($Equipment as $EquipmentKey=>$EquipmentValue){
                    //获取工单
                    $workOrderData['order_number'] = workOrderNumber();
                    $workOrderData['business_id'] = 1;
                    $workOrderData['service_address'] = $value['province'].$value['city'].$value['area'].$EquipmentValue['equipments_address'];
                    $workOrderData['remarks'] = '【系统】自动生成续费工单';
                    $result_work_info = $WorkOrder->insertId($workOrderData,'系统',0,$EquipmentValue['id'],'系统');
                    if ($result_work_info){
                        writelog(0,'系统','【操作成功】系统自动生成续费工单，续费工单号：'.$workOrderData['order_number'],1,'admin_log');
                    }else{
                        writelog(0,'系统','【操作失败】系统自动生成续费工单失败，请手动生成工单',0,'admin_log');
                    }
                }
            }


            //换芯时间
            if ($value['for_core_time'] + $one_month_time <= $time && $value['is_Core'] != 1){
                $updateData['is_Core'] = 1;
                //更新状态
                $result = $Contract->updateContractExpire($where,$updateData);
                if ($result != 0){
                    $Log['contract_id'] = $value['contract_id'];
                    $Log['new_value'] = '换芯时间即将到期';
                    //添加日志
                    $Contract->addContractLogExpire($Log);
                }
                //派发换芯工单
                foreach ($Equipment as $EquipmentKey=>$EquipmentValue){
                    //获取工单
                    $workOrderData['order_number'] = workOrderNumber();
                    $workOrderData['business_id'] = 2;
                    $workOrderData['service_address'] = $value['province'].$value['city'].$value['area'].$EquipmentValue['equipments_address'];
                    $workOrderData['remarks'] = '【系统】自动生成换芯工单';
                    $result_work_info = $WorkOrder->insertId($workOrderData,'系统',0,$EquipmentValue['id'],'系统');
                    if ($result_work_info){
                        writelog(0,'系统','【操作成功】系统自动生成换芯工单，换芯工单号：'.$workOrderData['order_number'],1,'admin_log');
                    }else{
                        writelog(0,'系统','【操作失败】系统自动生成换芯工单失败，请手动生成工单',0,'admin_log');
                    }
                }
            }
            //销毁已使用数据（防止内存溢出）
            unset($EquipmentWhere);
            unset($Equipment);
            unset($where);
            unset($Log);
        }
            // 提交事务
            Db::commit();
            return date('Y-m-d H:i:s')." Completion of enforcement";
        }catch (\Exception $e){
            echo $e."<br>";
            // 事务回滚
            Db::rollback();
            return date('Y-m-d H:i:s')." Error:Failure to automatically distribute work orders";
        }
    }
}